/*
 * @Author         : mli
 * @Email          : mli@poptown.io
 * @Description    : 
 * @FilePath       : /lib/utils/throttle.dart
 * @Date           : 2024-03-05 16:08:32
 * @LastEditTime: 2024-03-25 12:16:25
 * @LastEditors: mli mli@poptown.io
 */
import 'dart:async';

import 'package:gameplay_flutter/lib_runtime/logger.dart';
// import 'package:soulalign_base/common/common.dart';

typedef VoidCallback = void Function();
typedef VoidCallbackT<T> = void Function(T);
typedef CallbackT2<T, U, W> = W? Function(T, U);

/// 接收一个函数function和一个延迟时间delay作为参数
/// 然后，它返回一个新的函数target。
/// 当你调用target函数时，如果距离上次调用的时间小于delay，
/// 则不会执行function。否则，它会执行function并重置计时器
VoidCallback throttle(VoidCallback function, Duration delay) {
  Timer? timer;
  target() {
    if (timer?.isActive ?? false) {
      RLog.w('throttle: timer is active');
      return;
    }
    timer = Timer(delay, () {});
    function();
  }

  return target;
}

/// 同throttle，但接收一个带参数的函数function
VoidCallbackT<T> throttle1<T>(VoidCallbackT<T> function, Duration delay) {
  Timer? timer;
  target(T t) {
    if (timer?.isActive ?? false) {
      RLog.w('throttle1: timer is active');
      return;
    }
    timer = Timer(delay, () {});
    function(t);
  }

  return target;
}

CallbackT2<T, U, W> throttle2<T, U, W>(
    CallbackT2<T, U, W> function, Duration delay) {
  Timer? timer;
  target(T t, U u) {
    if (timer?.isActive ?? false) {
      RLog.w('throttle2: timer is active');
      return null;
    }
    timer = Timer(delay, () {});
    return function(t, u);
  }

  return target;
}
